// src/auth/auth.service.ts
import {
  ConflictException,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { User } from 'src/schemas/user.schema';
import { UserService } from 'src/modules/user/user.service';
import axios from 'axios';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {}

  // 用户注册
  async register(phone: string, password: string) {
    try {
      const user = await this.userService.create({
        phone,
        password,
      });
      return this.generateTokens(user);
    } catch (err) {
      if (err.code === 11000) {
        throw new ConflictException('手机号已被注册');
      }
      throw err;
    }
  }

  // 手机号登录
  async login(phone: string, password: string) {
    const user = await this.userService.findByPhone(phone);

    if (!user || !(await user.comparePassword(password))) {
      throw new UnauthorizedException('手机号或密码错误');
    }

    return this.generateTokens(user);
  }

  async wechatLogin(code: string) {
    const wxRes = await axios.get(
      'https://api.weixin.qq.com/sns/jscode2session',
      {
        params: {
          appid: process.env.WX_APPID,
          secret: process.env.WX_SECRET,
          js_code: code,
          grant_type: 'authorization_code',
        },
      },
    );

    const openid = wxRes.data.openid;
    const user = await this.userService.createWechat(openid);

    return this.generateTokens(user);
  }

  // 生成访问令牌
  private generateTokens(user: User) {
    const payload = { userId: user._id };

    return {
      token: this.jwtService.sign(payload, {
        secret: process.env.JWT_SECRET,
      }),
    };
  }
}
